
import { controller, action, routeData, Controller, request, response } from "maishu-node-mvc";
import { PermissionService } from "maishu-services-sdk";
import Cookies = require("cookies");
import { AjaxOptions } from "maishu-chitu-service";
import { merchantRoleId } from "../global";

@controller("/")
export class LocalController extends Controller {
    ps: PermissionService;
    token: string;

    constructor() {
        super();

        this.ps = new PermissionService();
        let ajax = this.ps.ajax;
        this.ps.ajax = (url: string, options?: AjaxOptions) => {
            if (this.token) {
                options.headers = options.headers || {};
                options.headers["token"] = this.token;
            }

            return ajax.apply(this.ps, [url, options])
        }
    }

    @action()
    async login(@routeData { username, password }, @request req, @response res) {
        let r = await this.ps.user.login(username, password);
        let cookies = new Cookies(req, res);
        cookies.set("token", r.token);
        return r;
    }

    @action()
    async me(@request req, @response res) {
        let cookies = new Cookies(req, res);
        this.token = cookies.get("token");
        let me = await this.ps.user.me();
        return me;
    }

    @action()
    async register(@routeData { mobile, password, smsId, verifyCode }) {
        let r = await this.ps.user.register(mobile, password, smsId, verifyCode);
        this.ps.user.update({ id: r.userId, role_id: merchantRoleId });
    }


}